<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-充值审核 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\common\model;
use app\api\controller\PublicApi;
use think\facade\Db;
use app\api\controller\Index;

class CardsTrans extends Common
{
    //---------------------------------------------后端---------------------------------------------------------------
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdmin($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where ="1=1";
        if(isset($post['user_name']) && !empty($post['user_name'])){
            //$where[] = ['username', '=', trim($post['user_name'])];
            $where .= " and username ='" . trim($post['user_name']) . "'";
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            //$where[] = ['ct.card_num', '=', trim($post['card_num'])];
            $where .= " and ct.card_num ='" . trim($post['card_num']) . "'";
        }
        if(isset($post['desc']) && !empty($post['desc'])){
            //$where[] = ['ct.desc', 'like', '%' . trim($post['desc']) . '%'];
            $where .= " and ct.desc like '" . '%' . trim($post['desc']) . '%' . "'";
        }
        if(isset($post['card_type']) && !empty($post['card_type'])){
            //$where[] = ['ct.desc', 'like', '%' . trim($post['desc']) . '%'];
            $where .= " and ct.card_num like '" . trim($post['card_type']) . '%' . "'";
        }
        if(isset($post['tran_status']) && !empty($post['tran_status'])){
            //$where[] = ['ct.tran_status', '=', trim($post['tran_status'])];
            $where .= " and ct.tran_status ='" . trim($post['tran_status']) . "'";
        }
        if(isset($post['appCode']) && !empty($post['appCode'])){
            //$where[] = ['ct.tran_status', '=', trim($post['tran_status'])];
            $where .= " and ct.app_code ='" . trim($post['appCode']) . "'";
        }
        if(isset($post['reversal_flag']) && !empty($post['reversal_flag'])){
            //$where[] = ['ct.reversal_flag', '=', $post['reversal_flag']];
            $where .= " and ct.reversal_flag ='" . $post['reversal_flag'] . "'";
        }
        if(isset($post['abort_amount']) && strlen($post['abort_amount'])>0){
            //$where[] = ['ct.shopping', 'like', '%' . trim($post['shopping']) . '%'];
            if(empty($post['amount'])){
                $input_amount = 0;
            }else{
                $input_amount = trim($post['amount']);
            }
            if($post['abort_amount'] == 1){
                $where .= " and ct.amount_auth = " . $input_amount;
            }else if($post['abort_amount'] == 2){
                $where .= " and ct.amount_auth >= " . $input_amount;
            }
        }
        if(isset($post['shopping']) && !empty($post['shopping'])){
            //$where[] = ['ct.shopping', 'like', '%' . trim($post['shopping']) . '%'];
            $where .= " and ct.shopping like '" . '%' . trim($post['shopping']) . '%' . "'";
        }
        if(isset($post['card_token']) && !empty($post['card_token'])){
            $card_num = Db::name('cards')->where(['card_token'=>trim($post['card_token'])])->value('card_num');
            $where .= " and ct.card_num ='" . $card_num . "'";
        }
        if(isset($post['bank_type']) && strlen($post['bank_type'])>0){
            //$where[] = ['ct.bank_type', '=', $post['bank_type']];
            if($post['bank_type'] == 3){
                $where .= " and ct.bank_type = 3";
            }else{
                $where .= " and ct.bank_type != 3";
            }
        }
        if(isset($post['Credit_556766']) && strlen($post['Credit_556766'])>0){
            if($post['Credit_556766'] == 1){
                $where .= " and substr(card_num,1,6) != '556766'";
            }else{
                $where .= " and substr(card_num,1,6) = '556766'";
            }
        }

        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode(' _ ' , $post['datetime']);
            $start_time = $time_list[0] . " 00:00:00";
            $end_time   = $time_list[1] . " 23:59:59";
            //$where[] = ['ct.ctime', 'between', "{$start_time},{$end_time}"];
            $where .= " and (ct.ctime between '{$start_time}' and '{$end_time}')";
        }
        $list = Db::name('cards_trans')->alias('ct')
            ->leftJoin('user u' , 'u.id=ct.user_id')
            ->field('u.username,ct.*')
            ->order('ct.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function tableDataAdminNew($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where ="1=1";
        if(isset($post['bank_type']) && strlen($post['bank_type'])>0){
            if($post['bank_type'] == 3){
                $where .= " and bank_type = 3";
            }else{
                $where .= " and bank_type != 3";
            }
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            $where .= " and card_num ='" . trim($post['card_num']) . "'";
        }
        if(isset($post['tran_status']) && !empty($post['tran_status'])){
            $where .= " and tran_status ='" . trim($post['tran_status']) . "'";
        }

        $list = Db::name('cards_trans_new')
            ->order('ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function tableDataShop($post)
    {
        $list_rows = $post['limit'] ?? config('paginate.list_rows');
        $page = $post['page'] ?? config('paginate.page');

        $where = '1=1';
        if(isset($post['shop_name']) && !empty($post['shop_name'])){
            $shop_name = strtolower($post['shop_name']);
            $where .= " and shop like '%{$shop_name}%'";
        }
        $list = Db::name('cards_trans_shop')
            ->order('amount desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();

        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public function getShops($ctime)
    {
        $where = "(tran_status ='Authorized' or tran_status ='Posted') and reversal_flag ='N'";
        $list = Db::name('cards_trans')
            ->where($where)
            ->field('tran_status,amount_auth,amount_post,shopping')
            ->order('ctime desc')
            ->select()
            ->toArray();
        $array_1 = [];
        $array_2 = [];
        $array   = [];
        $re = '';
        if($list){
            foreach($list as $v){
                if($v['tran_status'] == 'Authorized'){
                    if(isset($array_1[$v['shopping']])){
                        $array_1[$v['shopping']] += $v['amount_auth'];
                        $array_2[$v['shopping']] += 1;
                    }else{
                        $array_1[$v['shopping']] = $v['amount_auth'];
                        $array_2[$v['shopping']] = 1;
                    }
                }else{
                    if(isset($array_1[$v['shopping']])){
                        $array_1[$v['shopping']] += $v['amount_post'];
                        $array_2[$v['shopping']] += 1;
                    }else{
                        $array_1[$v['shopping']] = $v['amount_post'];
                        $array_2[$v['shopping']] = 1;
                    }
                }
            }
            foreach ($array_1 as $k_a => $v_a){
                $array[] = [
                    'shop' => $k_a ,
                    'amount' => round($v_a,2) ,
                    'num' => $array_2[$k_a] ,
                    'ctime'=>$ctime];
            }
            $age = array_column($array, 'amount');
            array_multisort($age, SORT_DESC, $array);
            Db::name('cards_trans_shop')->where('id >0')->delete();
            $re = Db::name("cards_trans_shop")->insertAll($array);
        }
        return $re;
    }

    public function getShopsUser($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        if(isset($post['shop_name']) && !empty($post['shop_name'])){
            $where = "(tran_status ='Authorized' or tran_status ='Posted' or tran_status ='Declined') and reversal_flag ='N'";

            $shop_name = strtolower($post['shop_name']);
            $where .= " and lower(shopping) like '%{$shop_name}%'";

            if(isset($post['datetime']) && !empty($post['datetime'])){
                $time_list = explode('_' , $post['datetime']);
                $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
                $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
                $where .=  " and (ctime between {$start_time} and {$end_time})";
            }

            $list = Db::name('cards_trans')
                ->where($where)
                ->field('tran_status,amount_auth,amount_post,shopping,user_id,reversal_flag')
                ->order('ctime desc')
                ->select()
                ->toArray();
            $array_1 = [];
            $array   = [];
            $array_Declined = [];
            if($list){
                foreach($list as $v){
                    //获取实际消费金额
                    if($v['tran_status'] == 'Authorized'|| $v['tran_status'] == 'Posted'){
                        if(isset($array_1[$v['user_id']])){
                            $array_1[$v['user_id']]['amount'] += ($v['tran_status'] == 'Authorized') ? $v['amount_auth']:$v['amount_post'];
                            $array_1[$v['user_id']]['num']    += 1;
                        }else{
                            $array_1[$v['user_id']]['amount'] = ($v['tran_status'] == 'Authorized') ? $v['amount_auth']:$v['amount_post'];
                            $array_1[$v['user_id']]['num']    = 1;
                        }
                    }
                    //获取拒付总笔数以及金额
                    if($v['tran_status'] == 'Declined'){
                        if(isset($array_Declined[$v['user_id']])){
                            $array_Declined[$v['user_id']]['amount'] += $v['amount_auth'];
                            $array_Declined[$v['user_id']]['num']    += 1;
                        }else{
                            $array_Declined[$v['user_id']]['amount'] = $v['amount_auth'];
                            $array_Declined[$v['user_id']]['num']    = 1;
                        }
                    }

                }
                //用户充值credit
                $fund_credit_list = Db::name('fund_check')->field("sum(amount) amount , user_id")
                    ->where("check_status = 1 and type = 0 and user_id !=1")->group('user_id')->select()->toArray();
                $new_fund_credit_list = [];
                foreach ($fund_credit_list as $k_credit => $v_credit){
                    $new_fund_credit_list[$v_credit['user_id']] = $v_credit['amount'];
                }
                //var_dump(count($new_fund_credit_list));
                //充值总额-Debit
                $fund_list_debit = Db::name('fund_check')->field("sum(amount) amount , user_id")
                    ->where("check_status = 1 and type = 1 and user_id !=1")->group('user_id')->select()->toArray();
                $new_fund_debit_list = [];
                foreach ($fund_list_debit as $k_debit => $v_debit){
                    $new_fund_debit_list[$v_debit['user_id']] = $v_debit['amount'];
                }
                //卡
                $card_balance_array = [];
                $card_num_array = [];
                $card_list = Db::name('cards')->field('sum(balance) balance,user_id,count(*) num')->group('user_id')->select()->toArray();
                foreach ($card_list as $k_card=>$v_card){
                    $card_balance_array[$v_card['user_id']] = $v_card['balance'];
                    $card_num_array[$v_card['user_id']] = $v_card['num'];
                }
                //用户属性
                $user_array = [];
                $user_balance_array = [];
                $user_list = Db::name('user')->field('id,username,balance')->select()->toArray();
                foreach ($user_list as $k=>$v){
                    $user_array[$v['id']] = $v['username'];
                    $user_balance_array[$v['id']] = $v['balance'];
                }
                //退款笔数  退款总金额
                //①银1实际退款
                $credit_1_array = [];
                $credit_1_list  = Db::name('cards_trans_credit')
                    ->field('user_id,amount')
                    ->where("credit_status = 1 and lower(shopping) like '%{$shop_name}%'")->select()->toArray();
                foreach ($credit_1_list as $k_credit_1 => $v_credit_1){
                    if(isset($credit_1_array[$v_credit_1['user_id']])){
                        $credit_1_array[$v_credit_1['user_id']]['amount'] += $v_credit_1['amount'];
                        $credit_1_array[$v_credit_1['user_id']]['num']    += 1;
                    }else{
                        $credit_1_array[$v_credit_1['user_id']]['amount'] = $v_credit_1['amount'];
                        $credit_1_array[$v_credit_1['user_id']]['num']    = 1;
                    }
                }
                //②银556实际退款
                $credit_556_array = [];
                $credit_556_list  = Db::name('cards_trans_credit_cd')
                    ->field('user_id,amount')
                    ->where("credit_status = 1 and lower(shopping) like '%{$shop_name}%'")->select()->toArray();
                foreach ($credit_556_list as $k_credit_556 => $v_credit_556){
                    if(isset($credit_556_array[$v_credit_556['user_id']])){
                        $credit_556_array[$v_credit_556['user_id']]['amount'] += $v_credit_556['amount'];
                        $credit_556_array[$v_credit_556['user_id']]['num']    += 1;
                    }else{
                        $credit_556_array[$v_credit_556['user_id']]['amount'] = $v_credit_556['amount'];
                        $credit_556_array[$v_credit_556['user_id']]['num']    = 1;
                    }
                }
                //③银3实际退款
                $credit_3_array = [];
                $credit_3_list  = Db::name('cards_trans_credit_lss')
                    ->field('user_id,amount')
                    ->where("credit_status = 1 and lower(shopping) like '%{$shop_name}%'")->select()->toArray();
                foreach ($credit_3_list as $k_credit_3 => $v_credit_3){
                    if(isset($credit_3_array[$v_credit_3['user_id']])){
                        $credit_3_array[$v_credit_3['user_id']]['amount'] += $v_credit_3['amount'];
                        $credit_3_array[$v_credit_3['user_id']]['num']    += 1;
                    }else{
                        $credit_3_array[$v_credit_3['user_id']]['amount'] = $v_credit_3['amount'];
                        $credit_3_array[$v_credit_3['user_id']]['num']    = 1;
                    }
                }

                //获取费率充值，开卡，退款
                $open_card_rate_array = [];
                $fund_rate_array      = [];
                $credit_rate_array    = [];
                $user_set_list = Db::name('user_set')
                    ->field('user_id,card_set')->select()->toArray();
                foreach ($user_set_list as $v_us){
                    $user_id  = $v_us['user_id'];
                    $card_set = json_decode($v_us['card_set'] , true);
                    foreach($card_set as $v_cs){
                        $open_amount = $v_cs['open_amount'];
                        $rate_refund = $v_cs['rate_refund'];
                        $rate_fund   = $v_cs['rate_fund'];
                        if(isset($open_card_rate_array[$user_id])){
                            if($open_card_rate_array[$user_id] - $open_amount >0){
                                $open_card_rate_array[$user_id] = $open_amount;
                            }
                        }else{
                            $open_card_rate_array[$user_id] = $open_amount;
                        }

                        if(isset($fund_rate_array[$user_id])){
                            if($fund_rate_array[$user_id] - $rate_fund >0){
                                $fund_rate_array[$user_id] = $rate_fund;
                            }
                        }else{
                            $fund_rate_array[$user_id] = $rate_fund;
                        }

                        if(isset($credit_rate_array[$user_id])){
                            if($credit_rate_array[$user_id] - $rate_refund >0){
                                $credit_rate_array[$user_id] = $rate_refund;
                            }
                        }else{
                            $credit_rate_array[$user_id] = $rate_refund;
                        }
                    }
                }

                foreach ($array_1 as $k_a => $v_a){
                    $new_fund_credit = $new_fund_credit_list[$k_a] ?? 0;
                    $new_fund_debit = $new_fund_debit_list[$k_a] ?? 0;

                    $declined_amount = $array_Declined[$k_a]['amount'] ?? 0;
                    $declined_amount = ($declined_amount != 0) ? getSprintf(round($declined_amount,2)) : $declined_amount;

                    //20250212新增退款笔数  退款总金额
                    $credit_1_amount = $credit_1_array[$k_a]['amount'] ?? 0;
                    $credit_1_num    = $credit_1_array[$k_a]['num'] ?? 0;
                    $credit_556_amount = $credit_556_array[$k_a]['amount'] ?? 0;
                    $credit_556_num    = $credit_556_array[$k_a]['num'] ?? 0;
                    $credit_3_amount = $credit_3_array[$k_a]['amount'] ?? 0;
                    $credit_3_num    = $credit_3_array[$k_a]['num'] ?? 0;

                    $credit_amount_all = getSprintf(round($credit_1_amount + $credit_556_amount + $credit_3_amount,2));
                    $credit_num_all    = $credit_1_num + $credit_556_num + $credit_3_num;
                    $array[] = [
                        'user' => $user_array[$k_a] ,
                        'amount'        => getSprintf(round($v_a['amount'],2)) ,
                        'num'           => $v_a['num'],
                        'user_balance'  => $user_balance_array[$k_a] ,
                        'card_balance'  => $card_balance_array[$k_a],
                        'fund_amount'   => $new_fund_credit - $new_fund_debit,
                        'card_num'      => $card_num_array[$k_a],
                        'dec_amount'    => $declined_amount,
                        'dec_num'       => $array_Declined[$k_a]['num'] ?? 0,
                        'credit_amount' => $credit_amount_all,
                        'credit_num'    => $credit_num_all,
                        'open_rate'     => $open_card_rate_array[$k_a] ?? '5.00',
                        'fund_rate'     => $fund_rate_array[$k_a] ?? '0.05',
                        'credit_rate'   => $credit_rate_array[$k_a] ?? '0.05'
                    ];
                }

                $age = array_column($array, 'amount');
                switch ($post['sort_type']){
                    case 1:
                        $age = array_column($array, 'amount');
                        break;
                    case 2:
                        $age = array_column($array, 'dec_amount');
                        break;
                    case 3:
                        $age = array_column($array, 'credit_amount');
                        break;
                    case 4:
                        $age = array_column($array, 'credit_num');
                        break;
                }
                
                array_multisort($age, SORT_DESC, $array);
            }
        }else{
            $array = [];
        }
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $array,
            'count' => count($array),
        ];
    }

    public function tranState($post)
    {
        $where = "state != 'DECLINED' and reason != 'Card account verification success' and type != 'foreign transaction fee' ";
        $result =[];
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode('_' , $post['datetime']);
            $start_time = strtotime($time_list[0] . " 00:00:00") - 8*60*60;
            $end_time   = strtotime($time_list[1] . " 23:59:59") - 8*60*60;
            if(($end_time - $start_time - 24*60*60) > 0){
                return [
                    'code'  => 0,
                    'msg'   => lang('get info success'),
                    'data'  => $result,
                    'count' => count($result),
                ];
            }
            $where  .= " and (ctime between {$start_time} and {$end_time})";
            $list = Db::name('cards_transactions')
                ->field('tran_token,ctime,type,state')
                ->order('ctime desc')
                ->where($where)->select()
                ->toArray();

            foreach($list as $k=>$v){
                $api_json =Index::searchUserStateDiff([
                    'add_url'   => '/transactions/' . $v['tran_token'],
                    'method'    => 'GET',
                    'request_data' => ''
                ]);
                if(isset($api_json['blog']) && $api_json['blog']){
                    $response = json_decode($api_json['response'] , true);
                    $state    = $response['state'];
                    if($v['type'] == 'authorization'){
                        if($state != 'PENDING'){
                            $result[] = $v;
                        }
                    }else if($v['type'] == 'refund'){
                        if($state != 'COMPLETION'){
                            $result[] = $v;
                        }
                    }else if($v['type'] == 'authorization.clearing' ||
                        $v['type'] == 'authorization.reversal' ||
                        $v['type'] == 'authorization.reversal.issuerexpiration')
                    {
                        if($state != 'CLEARED'){
                            $result[] = $v;
                        }
                    }
                }
            }
            return [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $result,
                'count' => count($result),
            ];
        }else{
            return [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $result,
                'count' => count($result),
            ];
        }
    }

    public static function getTotalDeposit()
    {
        $list =  Index::searchOtherAdmin([
            'add_url'       => '/programreserve/transactions?count=100&start_index=0',
            'method'        => 'GET',
            'request_data'  => ''
        ]);
        $blog   = $list['blog'] ?? '';
        $count      = 0;
        $data       = [];
        $sum_amount = 0;
        if($blog){
            $response = json_decode($list['response'] , true);
            if(isset($response['data'])){
                $data_1   = [];
                foreach ($response['data'] as $v){

                        $data_1['create_time']  = str_replace(array('T','Z'),' ',$v['created_time']);
                        $data_1['type']         = $v['type'];
                        $amount = $v['amount'];
                        if($v['type'] == 'DEBIT'){
                            $amount = -$amount;
                        }
                        $data_1['amount'] = $amount;
                        $sum_amount += $amount;
                        $data[] = $data_1;
                }
            }
            $count = count($data);
        }
        return [
            'data'      => $data,
            'count'     => $count,
            'sum_amount'=> $sum_amount,
        ];
    }

    public function getCardShops($post)
    {
        $where = "(tran_status ='Authorized' or tran_status ='Posted') and reversal_flag ='N'";
        if(isset($post['shopping']) && !empty($post['shopping'])){
            $shop_name_old = trim($post['shopping']);
            $shop_name = strtolower($shop_name_old);
            $where .= " and lower(shopping) like '%{$shop_name}%'";
            $list = Db::name('cards_trans')
                ->where($where)
                ->field('shopping,card_num,ctime')
                ->order('ctime desc')
                ->select()
                ->toArray();
            $array_1 = [];
            $array_2 = [];
            $array   = [];
            if($list){
                foreach($list as $v){
                    $card_num_4 = substr($v['card_num'] , 0 , 6);
                    if(isset($array_1[$card_num_4])){
//                        if(!in_array($v['shopping'] , $array_1[$card_num_4]['type'])){
//                            $array_1[$card_num_4]['type'][] = $v['shopping'];
//                        }
                        $array_1[$card_num_4]['num'] += 1;
                    }else{
//                        $array_1[$card_num_4]['type'][] = $v['shopping'];
                        $array_1[$card_num_4]['num'] = 1;
                        $array_1[$card_num_4]['time'] = $v['ctime'];
                    }
                    if(!isset($array_1[$card_num_4]['type'])){
                        $array_1[$card_num_4]['type'] = $v['shopping'];
                    }
                }
                foreach ($array_1 as $k_a => $v_a){
                    $array[] = [
                        'card_type'     => $k_a ,
                        'shopping'      => $v_a['type'] ,
                        'success_num'   => $v_a['num'],
                        'ctime'         => $v_a['time'],
                        ];
                }
            }

            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $array,
                'count' => count($array),
            ];
        }else{
            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => [],
                'count' => 0,
            ];
        }
    }

    public function getSearchShops($post)
    {
        $user_id = $post['user_id'];
        $where = "(tran_status ='Authorized' or tran_status ='Posted') and reversal_flag ='N'";
        if(isset($post['shopping']) && !empty($post['shopping'])){
            $shop_name_old = trim($post['shopping']);
            $search = array('\'');
            $shop_name_old = str_replace($search, '',$shop_name_old);
            Db::name('key_log')->save([
                'user_id'   => $user_id,
                'param'     => $shop_name_old,
                'ctime'     => getUtcTime()
            ]);
            $shop_name = strtolower($shop_name_old);
            $where .= " and lower(shopping) like '%{$shop_name}%' ";
            //判断是否包含openai 单个或者多个字符串
            if(strstr('openai' , strtolower($shop_name))){
                $where .= " and amount_auth > 0 ";
            }
            $list = Db::name('cards_trans')
                ->where($where)
                ->field('shopping,card_num,ctime')
                ->order('ctime desc')
                ->select()
                ->toArray();
            $array_1 = [];
            $array_2 = [];
            $array   = [];
            if($list){
                foreach($list as $v){
                    $card_num_4 = substr($v['card_num'] , 0 , 6);
                    if(isset($array_1[$card_num_4])){
//                        if(!in_array($v['shopping'] , $array_1[$card_num_4]['type'])){
//                            $array_1[$card_num_4]['type'][] = $v['shopping'];
//                        }
                        $array_1[$card_num_4]['num'] += 1;
                    }else{
//                        $array_1[$card_num_4]['type'][] = $v['shopping'];
                        $array_1[$card_num_4]['num'] = 1;
                        $array_1[$card_num_4]['time'] = $v['ctime'];
                    }
                    if(!isset($array_1[$card_num_4]['type'])){
                        $array_1[$card_num_4]['type'] = $v['shopping'];
                    }
                }
                foreach ($array_1 as $k_a => $v_a){
                    $array[] = [
                        'card_type'     => $k_a ,
                        'shopping'      => $v_a['type'] ,
                        'success_num'   => $v_a['num'],
                        'ctime'         => $v_a['time'],
                    ];
                }
            }

            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $array,
                'count' => count($array),
            ];
        }else{
            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => [],
                'count' => 0,
            ];
        }
    }

    /**
     * 更新卡消费日志
     * @param $card_list
     */
    public static function apiUpCardTran($card_list)
    {
        //获取要查询的消费日志 开始时间和结束时间
        $today_time     = getUtcTime();
        $start_time     = date("Y-m-d",strtotime("-44 day"));
        $end_time       = date('Y-m-d' , $today_time);

        $card_id            = $card_list['id'];
        $user_id            = $card_list['user_id'];
        $card_status        = $card_list['status'];
        $card_type          = $card_list['card_type'];
        $balance_account    = $card_list['balance_account'];
        $bank_type          = $card_list['bank_type'];
        $card_balance       = $card_list['balance'];
        $card_num           = $card_list['card_num '];

        $create_card_param      = [
            "user_id"       => $user_id,
            "action_type"   => "search_trans_test",
            "card_type"     => $card_type,
            "bank_type"     => $bank_type,
            "post_param"  => [
                "card_num"   => $card_num,
                "startDate"  => $start_time,
                "endDate"    => $end_time,
            ]
        ];
        $request_api= PublicApi::requestApi("Comdata",$create_card_param);
        $blog       = $request_api['blog'] ?? false;
        if($blog){
            Db::startTrans();
            try {

                //获取所有卡的卡号
                $card_list = Db::name('cards')->select()->toArray();
                $card_array         = [];
                $userIdArray        = [];
                $cardStatusArray    = [];
                foreach ($card_list as $v_card){
                    $card_array[]                           = $v_card['card_num'];
                    $userIdArray[$v_card['card_num']]       = $v_card['user_id'];
                    $cardStatusArray[$v_card['card_num']]   = $v_card['status'];
                }
                $list = $request_api['list'];
                $history_status = ['Authorized','Posted','Declined','Credit'];
                foreach ($list as $k=>$v){
                    $cardNumber = $v['cardNumber'];
                    if(in_array($cardNumber , $card_array)){
                        $postedDate = $v['postedDate'] ?? '';
                        $utime      = !empty($postedDate) ? $v['postedDate'] . ' ' . $v['postedTime'] : '';
                        $shopping   = $v['acceptLocation'] ?? '';
                        $ctime      = $v['transactionDate'] . ' ' . $v['transactionTime'];
                        $reversalFlag = $v['reversalFlag'];
                        $current_status = $v['transactionStatus'];
                        $preAuthAmount  = $v['preAuthAmount'];
                        $idMatchNumber  = $v['idMatchNumber'] ?? '';
                        $correctiveAction = '';
                        if($v['transactionStatus'] == 'Declined'){
                            $correctiveAction = $v['correctiveAction'] ?? '';
                            if(empty($correctiveAction)){
                                $correctiveAction = $v['declineMessage'] ?? '';
                            }
                        }
                        $user_id  = $userIdArray[$cardNumber] ?? 0;

                        Db::name('cards_trans')->save([
                            'app_code'      => $v['approvalCode'],
                            'card_num'      => $cardNumber,
                            'user_id'       => $user_id,
                            'tran_status'   => $current_status,
                            'amount_auth'   => $preAuthAmount,
                            'amount_post'   => $v['postedAmount'],
                            'shopping'      => $shopping,
                            'desc'          => $correctiveAction,
                            'reversal_flag' => $reversalFlag,
                            'ctime'         => $ctime,
                            'utime'         => $v['transactionStatus'] == 'Declined' ? '' : $utime,
                            'bank_type'     => $bank_type
                        ]);
                        if($current_status == 'Credit' && !empty($idMatchNumber)) {
                            //只累加最新的Credit数据
                            $abs_amount = abs($v['postedAmount']);
                            $cardit_add = [
                                'card_num'      => $cardNumber,
                                'amount'        => $abs_amount,
                                'ctime'         => $ctime,
                                'idMatchNumber' => $idMatchNumber,
                                'user_id'       => $user_id,
                                'shopping'      => $shopping
                            ];
                            if ($card_type == '556766') {
                                $credit_list = Db::name('cards_trans_credit_cd')->where([
                                    'card_num' => $cardNumber,
                                    'idMatchNumber' => $idMatchNumber,
                                    'amount'    => $abs_amount
                                ])->find();
                                if(empty($credit_list)){
                                    $credit_result = CardsTransCredit::endCredit([
                                        'card_num'      =>  $cardNumber,
                                        'user_id'       =>  $user_id,
                                        'credit_amount' =>  $abs_amount,
                                        'shopping'      =>  $shopping,
                                    ] , 2);
                                    if($credit_result){
                                        $credit_server_set = UserSet::getCardSet($user_id);
                                        $credit_server_set_rate = $credit_server_set[$bank_type][$card_type]['rate_refund'];
                                        $credit_server_amount = getSprintf(round($abs_amount * $credit_server_set_rate,2));
                                        $cardit_add += [
                                            'credit_status' => 1,
                                            'utime' => getUtcTime(),
                                            'server_amount' => $credit_server_amount
                                        ];
                                    }
                                    Db::name('cards_trans_credit_cd')->save($cardit_add);
                                }
                            }else {
                                $credit_list = Db::name('cards_trans_credit')->where([
                                    'card_num' => $cardNumber,
                                    'idMatchNumber' => $idMatchNumber,
                                    'amount'    => $abs_amount
                                ])->find();
                                if(empty($credit_list)){
                                    Db::name('cards_trans_credit')->save($cardit_add);
                                }
                            }
                        }
                        if(!in_array($current_status,$history_status)){
                            $data_param = json_encode(['card_num'=>$cardNumber,'card_status'=>$current_status]);
                            if(!Db::name('api_error')->where(['data_param'=>$data_param])->find()){
                                Db::name('api_error')->save([
                                    'user_id'       => 0,
                                    'amount'        => $v['preAuthAmount'],
                                    'amount_bank'   => $v['preAuthAmount'],
                                    'type'          => 'card_total_comparison',
                                    'data_param'    => [''],
                                    'ctime'         => getUtcTime(),
                                    'is_rep'        => 1
                                ]);
                            }
                        }
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                $error_msg = $e->getMessage();
                var_dump($error_msg);
                Db::rollback();
            }
        }



    }
}